<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use DB;

class UserController extends Controller
{
    
    public function index(Request $request)
    {
        //保存搜索条件
        $where = [];
        //实例化要操作的表
        $db = DB::table('user');
        //判断有没有搜索name字段的值
        if($request->has('name')){
            // 获取要搜索的name字段的值
    	    $name = $request->input('name');
    	    //添加where模糊匹配条件
    	    $db->where('name','like',"%{$name}%");
    	    $where['name'] = $name;
        }
    	// 分页
    	$list = $db->paginate(1);
    	//加载模板
    	return view('user.index',['list'=>$list,'where'=>$where]);
    }
    //添加
    public function create()
    {
        return view('user.add');
    }

    public function store(Request $request)
    {
    	//自动规则
		//dd($request);
    	$messages = [
    		'required' => ':attribute 的字段是必要的',
			
    	];
    	//
    	$this->validate($request, [
	        'name' => 'required|unique:user|max:16',
	        'uemail' => 'required',
            'qq' => 'required|min:5|max:10',
			'password' => 'required|min:8|max:20',
	    ],$messages);
    	$data = $request->only('name','uemail','tel','qq','password','state');
    	$id = DB::table('user')->insertGetId($data);
    	if($id>0){
    		return redirect('user');
    	}
    }
    //删除
    public function destroy($id)
    {
    	$row = DB::table('user')->where('id',$id)->delete();
    	if($row>0){
    		return redirect('user');
    	}
    }
    //修改
    public function edit($id)
    {
    	$user = DB::table('user')->where('id',$id)->first();
    	
    	return view('user.edit',['user'=>$user]);
    }

    public function update($id,Request $request)
    {
    	$data = $request->only('name','uemail','tel','qq','password','state');
    	//dd($data);
    	$row = DB::table('user')->where('id',$id)->update($data);
    	
    	if($row>0){
    		return redirect('user');
    	}
    }
}
